﻿using System;
using System.Collections.Generic;
using Codemo.Core.Applications;
using Codemo.Core.Deployment.Tasks;

namespace Codemo.Core.Deployment
{
    /// <summary>
    /// 
    /// </summary>
    public class DeploymentService
    {
        /// <summary>
        /// Deploys the specified version.
        /// </summary>
        /// <param name="application">The application.</param>
        /// <param name="deploymentScriptsVersion">The deployment scripts version.</param>
        /// <param name="target">The target.</param>
        /// <param name="packageName">Name of the package.</param>
        public void Deploy(Application application, string deploymentScriptsVersion, string target, string packageName)
        {
            DeploymentConfigurationVersion version = application.FindVersion(deploymentScriptsVersion);

            DeploymentTarget deploymentTarget = GetTarget(version, target);

            var package = new Package(packageName, application.PackageRepositoryPath);

            //TODO inject dependency
            var factory = new TaskFactory();

            IList<DeploymentTask> tasks = factory.GenerateTasks(application, version, deploymentTarget, package);

            foreach (DeploymentTask task in tasks)
            {
                task.Execute();
            }
        }


        /// <summary>
        /// Gets the target.
        /// </summary>
        /// <param name="version">The version.</param>
        /// <param name="target">The target.</param>
        /// <returns></returns>
        private static DeploymentTarget GetTarget(DeploymentConfigurationVersion version, string target)
        {
            DeploymentTarget deploymentTarget;
            if (!version.DeploymentTargets.TryGetValue(target, out deploymentTarget))
            {
                throw new ArgumentException("Invalid target name", "target");
            }
            return deploymentTarget;
        }
    }
}